package com.pay.controller.admin;

import com.github.pagehelper.PageInfo;
import com.pay.common.base.BaseController;
import com.pay.common.domain.AjaxResult;
import com.pay.model.auto.PayAccount;
import com.pay.model.auto.PayAccountExample;
import com.pay.model.auto.PayOrder;
import com.pay.model.auto.PayOrderExample;
import com.pay.model.custom.TableSplitResult;
import com.pay.model.custom.Tablepar;
import com.pay.model.vo.PayVo;
import com.pay.service.PayAccountService;
import com.pay.service.PayOrderService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("pay")
@Api(value = "支付账户")
public class PayController extends BaseController {

    private String prefix = "admin/pay";

    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private PayAccountService payAccountService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping
    @ResponseBody
    public AjaxResult index(@RequestBody PayVo payVo, HttpServletRequest request ) {
        PayAccountExample example = new PayAccountExample();
        example.createCriteria().andPayTypeEqualTo(payVo.getPayType()).andPayStatusEqualTo(1);
        List<PayAccount> list = payAccountService.selectByExample(example);
        if(null == list || list.size() < 1){
            return error("未找到收款账户");
        }
        BigDecimal money = getPayMoney(payVo.getMoney());
        // 生成订单
        PayAccount payAccount = list.get(0);
        PayOrder payOrder = PayOrder.builder()
                .serialNumber(payAccount.getPayType().concat(String.valueOf(payAccount.getPayNumber())))
                .payType(payAccount.getPayType())
                .money(money)
                .payUrl(payAccount.getPayUrl())
                .payStatus(0)
                .returnUrl(payVo.getReturnUrl())
                .notifyUrl(payVo.getNotifyUrl())
                .valid(true)
                .createDate(new Date())
                .updateDate(new Date())
                .build();
        payOrderService.insertSelective(payOrder);
        // 支付链接
        StringBuffer url = request.getRequestURL();
        String payUrl = url.delete(url.length() - request.getRequestURI().length(), url.length())
                .append("/pay/payment/").append(payOrder.getId()).toString();
        return success().put("payUrl", payUrl);
    }

    /**
     * 获取不重复的金额
     * @param money
     * @return
     */
    private BigDecimal getPayMoney(BigDecimal money) {
        String key = "pay_money_".concat(String.valueOf(money));
        String payMoney = stringRedisTemplate.opsForValue().get(key);
        if(null == payMoney){

            PayOrderExample example = new PayOrderExample();
            example.createCriteria().andMoneyEqualTo(money).andPayStatusEqualTo(0);
            List<PayOrder> list = payOrderService.selectByExample(example);
            if(null != list && list.size() > 0){
                return getPayMoney(money.subtract(BigDecimal.valueOf(Double.valueOf(0.01))));
            }

            stringRedisTemplate.opsForValue().set(key, String.valueOf(money), 1, TimeUnit.MINUTES);
            return money;
        }
        return getPayMoney(money.subtract(BigDecimal.valueOf(Double.valueOf(0.01))));
    }

    /**
     * 支付页面
     * @param mmap
     * @param orderId
     * @return
     */
    @GetMapping("/payment/{orderId}")
    public String payment(ModelMap mmap, @PathVariable String orderId) {
        PayOrder payOrder = payOrderService.selectByPrimaryKey(orderId);
        mmap.put("order", payOrder);

        if(payOrder.getValid()){
            mmap.put("minute", "05");
        } else {
            mmap.put("minute", "00");
        }

        return prefix + "/pay";
    }

    @PostMapping("/update/list")
    @ResponseBody
    public Object list(Tablepar tablepar, BigDecimal searchTxt) {
        tablepar.setPageSize(5);
        PageInfo<PayOrder> page = payOrderService.list(tablepar, searchTxt);
        TableSplitResult<PayOrder> result = new TableSplitResult<PayOrder>(page.getPageNum(), page.getTotal(), page.getList());
        return result.getRows();
    }
}
